package org.linlinjava.litemall.db.handler;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

public class LocalTimeArrayTypeHandler extends BaseTypeHandler<List<LocalTime[]>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<LocalTime[]> parameter, JdbcType jdbcType) throws SQLException {
        String join = StrUtil.join(",", parameter);
        ps.setString(i,join);
    }

    @Override
    public List<LocalTime[]> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String timestampString = rs.getString(columnName);
        if (StrUtil.isEmpty(timestampString)) {
            return null;
        }
        String[] timestampArray = timestampString.split(",");
        return convertArrayToList(timestampArray);
    }

    @Override
    public List<LocalTime[]> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String timestampString = rs.getString(columnIndex);
        if (StrUtil.isEmpty(timestampString)) {
            return null;
        }
        String[] timestampArray = timestampString.split(",");
        return convertArrayToList(timestampArray);
    }

    @Override
    public List<LocalTime[]> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String timestampString = cs.getString(columnIndex);
        if (StrUtil.isEmpty(timestampString)) {
            return null;
        }
        String[] timestampArray = timestampString.split(",");
        return convertArrayToList(timestampArray);
    }

    private List<LocalTime[]> convertArrayToList(String[] timestampArray) throws SQLException {
        List<LocalTime[]> timeRanges = new ArrayList<>();
        for (int i = 0; i < timestampArray.length; i += 2) {
            LocalTime startTime = LocalTime.parse(timestampArray[i]);
            LocalTime endTime = LocalTime.parse(timestampArray[i + 1]);
            LocalTime[] timeRange = {startTime, endTime};
            timeRanges.add(timeRange);
        }
        return timeRanges;
    }
}
